import React, { useState, useEffect } from 'react';
import { Result, Divider, Button, message, Modal } from 'antd';
import { useAntdTable, useBoolean } from '@umijs/hooks';
import { connect } from 'dva';
import SlickTable from '@/components/SlickTable';
// import JumpConfig from './components/JumpConfig';
import request from '@/utils/request';
import styles from './index.less';

function UsoflowContent(props) {
  // 流程库组织树id对应版本列表查询
  const [treeId, setTreeId] = useState('');
  // 组织树类型判断 Package流程包  PackageCatalog目录
  const [treeType, setTreeType] = useState('PackageCatalog');
  // 版本列表选中项
  const [versionSelectId, setVersionSelectId] = useState('');
  // 当前为锁定状态才显示跃迁配置与环节拓展配置
  const [lock, setLock] = useState(false);

  /**
   *
   * @param {*} param0
   * 版本管理表单请求,页面为叶子节点 进行相关请求
   * 由于加载顺序问题，getVersionTable 方法会在useAntdTable 的时候进行调用
   * 解决：状态非叶子节点的时候返回个Promise 对象 但页面其实已经加载过 useAntdTable 所以直接关注依赖项变化即可
   */
  const getVersionTable = ({ current, pageSize, paramsObj }) => {
    return treeType !== 'Package'
      ? new Promise(function(resolve) {
          resolve({
            total: 0,
            data: [],
          });
        })
      : request('pmc/pms/PmOrderFlowDefController/queryPage', {
          data: {
            pageNum: current,
            pageSize,
            ...paramsObj,
          },
        }).then(res => {
          if (res.success) {
            if (Array.isArray(res.data.records)) {
              return {
                total: res.data.total,
                data: res.data.records.map(val => {
                  const { children, ...rest } = val;
                  return rest;
                }),
              };
            }
          }
          return {
            total: 0,
            data: [],
          };
        });
  };

  const { tableProps: versionTableProps, refresh } = useAntdTable(
    params => {
      return getVersionTable({ ...params, pageSize: 5, paramsObj: { packageId: treeId } });
    },
    [treeId],
    {
      defaultPageSize: 5,
    }
  );

  const { pagination: versionPagination, ...restVersionTableProps } = versionTableProps;

  /**
   * 环节管理级联版本管理
   */

  const getLinkTable = ({ current, pageSize, paramsObj }) => {
    // 如 为PackageCatalog目录及版本管理传的为空则不调用环节管理接口
    return treeType !== 'Package' || !versionSelectId
      ? new Promise(function(resolve) {
          resolve({
            total: 0,
            data: [],
          });
        })
      : request('pmc/pms/PmOrderFlowNodeController/queryPage', {
          data: {
            pageNum: current,
            pageSize,
            ...paramsObj,
          },
        }).then(res => {
          if (res.success) {
            if (Array.isArray(res.data.records)) {
              return {
                total: res.data.total,
                data: res.data.records.map(val => {
                  const { children, ...rest } = val;
                  return rest;
                }),
              };
            }
          }
          return {
            total: 0,
            data: [],
          };
        });
  };

  const { tableProps: linkTableProps, refresh: linkRefresh } = useAntdTable(
    params => {
      return getLinkTable({ ...params, pageSize: 5, paramsObj: { flowId: versionSelectId } });
    },
    [versionSelectId],
    {
      defaultPageSize: 5,
    }
  );

  const { pagination: linkpagination, ...restLinkTableProps } = linkTableProps;
  /* eslint-disable */
  // 初始化默认加载第一条
  useEffect(() => {
    if (!versionSelectId) {
      const [head, ...other] = restVersionTableProps.dataSource;
      if (head) {
        setVersionSelectId(head.flowId);
        head.statusCd === '1200' ? setLock(true) : setLock(false);
      }
    }
  }, [restVersionTableProps.dataSource]);
  /* eslint-enable */
  /**
   * 默认获取版本管理表格数据如有数据拿第一条的id查询环境管理表格数据
   */

  useEffect(() => {
    if (!props.id) return;
    // 截取各个所需字段
    const curStatus = props.id.match(/,(\S*)/)[1];
    const curId = props.id.match(/(\S*),/)[1];
    const type = curId.match(/(\S*)_/)[1];
    const id = curId.match(/_(\S*)/)[1];
    setTreeType(type);
    setTreeId(id);
    setVersionSelectId('');
    setLock(false);
  }, [props.id]);

  // 版本管理选中项
  const rowSelect = record => {
    setVersionSelectId(record.flowId);
    if (record.statusCd === '1200') {
      setLock(true);
    } else {
      setLock(false);
    }
  };

  const setRowClassName = record => {
    return record.flowId === versionSelectId ? `${styles.clickRowStyle}` : '';
  };

  const updateStatusCd = record => {
    request('pmc/pms/PmOrderFlowDefController/updateStatusCd', {
      data: {
        flowId: record.flowId,
        statusCd: 1000,
      },
    }).then(res => {
      if (res.success) {
        message.success(`生效成功！`);
        refresh();
        setLock(false);
      } else {
        message.error(res.errMessage);
      }
    });
  };

  const renderView = (
    <>
      <div className="ant-detail-title">
        <span>版本管理</span>
        <span className="pull-right">
          <Button
            type="primary"
            onClick={() => {
              Modal.confirm({
                content: '此为usoflow流程，若要绘制流程，请跳转至usoflow创建。',
                onOk() {
                  props.goToStep(2, { type: 'add', refresh });
                },
                onCancel() {},
              });
            }}
          >
            新建
          </Button>
        </span>
      </div>
      <SlickTable
        style={{ marginTop: 8 }}
        rowKey={record => record.flowId}
        columns={[
          {
            title: '版本号',
            dataIndex: 'version',
            ellipsis: true,
          },
          {
            title: '版本状态',
            dataIndex: 'statusCdName',
            ellipsis: true,
          },
          {
            title: '版本操作',
            render: record => {
              return record.statusCd === '1000' ? (
                <span>此记录已生效</span>
              ) : (
                <a
                  onClick={() => {
                    updateStatusCd(record);
                  }}
                >
                  生效
                </a>
              );
            },
          },
        ]}
        {...restVersionTableProps}
        data={{
          pagination: {
            ...versionPagination,
            pageSize: 5,
          },
        }}
        onRow={record => {
          return {
            onClick: () => {
              rowSelect(record);
            },
          };
        }}
        rowClassName={setRowClassName}
      />
      <Divider className="small" />

      <div className="ant-detail-title">
        <span>环节管理</span>
      </div>
      <SlickTable
        style={{ marginTop: 8 }}
        rowKey={record => record.flowNodeId}
        columns={[
          {
            title: '环节编码',
            dataIndex: 'flowNodeCode',
            ellipsis: true,
          },
          {
            title: '是否首环节',
            dataIndex: 'isFirstNode',
            ellipsis: true,
            render: text => {
              return parseInt(text) === 0 ? '是' : '否';
            },
          },
          {
            title: '是否自动环节',
            dataIndex: 'isAuto',
            ellipsis: true,
            render: text => {
              return parseInt(text) === 0 ? '是' : '否';
            },
          },
          {
            title: '环节名称',
            dataIndex: 'flowNodeName',
            ellipsis: true,
          },
          {
            title: '关联表单编码',
            dataIndex: 'formName',
            ellipsis: true,
          },
          {
            title: '处理模式',
            dataIndex: 'operModeName',
            ellipsis: true,
          },
          {
            title: '工单状态',
            dataIndex: 'orderStateName',
            ellipsis: true,
          },
          {
            title: '设置事件数',
            dataIndex: 'planNum',
            ellipsis: true,
          },
          {
            title: '操作',
            width: 170,
            align: 'center',
            render: (text, record) => {
              return (
                <span>
                  <a
                    onClick={() => {
                      props.goToStep(4, { obj: { ...record, operType: 'detail' } });
                    }}
                  >
                    详情
                  </a>
                  {lock ? (
                    <>
                      <Divider type="vertical" />
                      <a
                        onClick={() => {
                          props.goToStep(4, {
                            obj: { ...record, operType: 'config' },
                            linkRefresh,
                          });
                        }}
                      >
                        环节拓展配置
                      </a>
                    </>
                  ) : null}
                </span>
              );
            },
          },
        ]}
        {...restLinkTableProps}
        data={{
          pagination: {
            ...linkpagination,
            pageSize: 5,
          },
        }}
      />
    </>
  );

  return <div className={styles.right_scroll_content}>{renderView}</div>;
}

export default connect(({ flowConfig }) => ({
  id: flowConfig.id,
}))(UsoflowContent);
